package com.wh;

public class ErFenfa {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,7,8};
        int a = 6;
        System.out.println(binarySearch(a,arr));
    }

    // 二分法查找
    static int binarySearch(int a, int[] arr) {
        int maxIndex = arr.length - 1;
        int minIndex = 0;
        int halfIndex = minIndex + (maxIndex - minIndex) / 2;
        while (minIndex <= maxIndex) {
            if (arr[halfIndex] == a) {
                return halfIndex;
            } else if (arr[halfIndex] < a) {
                minIndex = halfIndex + 1;
            } else {
                maxIndex = halfIndex - 1;
            }
            halfIndex = minIndex + (maxIndex - minIndex) / 2;
        }
        return -1;
    }
}
